<?php
namespace Admin\Controller;
// +----------------------------------------------------------------------
// | TAODUDU.COM  [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.taodudu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: ubten <462193409@qq.com> http://www.ubten.com/
// +----------------------------------------------------------------------
use Admin\Controller\AdminController;
use Libs\Logs;
header("content-type:text/html;charset=utf-8");

class OrderController extends AdminController{
    
    function _initialize() {
        parent::_initialize();
        $this->assign('sys', 'trade'); // 数据集
    }
    //订单列表
    public function index(){
        $order_sn = I('order_sn');
        $store_name = I('store_name');
        $order_state = I('order_state');
        $buyer_name = I('buyer_name');
        $payment_code = I('payment_code');
        $query_start_time = strtotime(I('query_start_time'));
        $query_end_time = strtotime(I('query_end_time'));
        if(!empty($query_end_time)){
            $query_end_time = time();
        }
        
        if(!empty($order_sn)){
            $where['oi.order_sn'] = $order_sn;
        }
        
        if(!empty($store_name)){
            $where['oi.store_name'] = array('like','%'.$store_name.'%');
        }
        
        if(!empty($buyer_name)){
            $where['os.reciver_name'] = array('like','%'.$buyer_name.'%');
        }
        
        if(!empty($order_state)){
            $where['oi.order_state'] = $order_state;
        }
         
        if(!empty($payment_code)){
            $where['oi.payment_code'] = $payment_code;
        }
        
        if(!empty($query_end_time) && !empty($query_end_time)){
            $where['oi.add_time'] = array('between',array($query_start_time,$query_end_time));
        }
        
        //SELECT * FROM tdd_order AS a LEFT JOIN tdd_order_common as b ON a.order_id = b.order_id where b.reciver_name LIKE '%李广%'
        $Order = M("Order");
        $count = $Order->alias('oi')->join('LEFT JOIN __ORDER_COMMON__ os ON oi.order_id = os.order_id')->where($where)->count();
        $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show(); // 分页显示输出
        $arr = $Order->alias('oi')->join('LEFT JOIN __ORDER_COMMON__ os ON oi.order_id = os.order_id')->where($where)->order('oi.order_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('pages',$show);
        $this->assign('arr',$arr);
        $this->assign('action', 'order');
        $this->display();

    }
    
    
    //订单详情
    public function  details(){
        if(IS_POST)
        {
            $order_id = I('post.order_id');
            $express_id =I('post.express_id');
            $order_state =I('post.order_state');
            $shipping_code =I('post.shipping_code');
            $id['order_id'] = $order_id;
            $logobj = new Logs();
                switch($data['order_state']){
                    case 0:$a = '取消';break;
                    case 10:$a = '待付款';break;
                    case 20:$a = '待发货';break;
                    case 30:$a = '已发货';break;
                    case 40:$a = '已完成';break;
                }
            $user_id = M('order')->where($id)->getField('user_id');
                
            $goods = M('order_goods')->where($id)->select();
            foreach ($goods as $value) {
                $goods_title  .= $value['goods_title'];
            }
            $goods_title = sub_str($goods_title, 0, 32);
            $data['order_state'] = $order_state;
            $data['shipping_code'] = $shipping_code;
            $data['express_id'] = $express_id;
            $re = M('order')->where($id)->save($data);
            if($re !== FALSE){
                //发送微信消息模版（如果用户的openid存在）
                $openID = M('weixin_user')->where('user_id='.$user_id)->getField('openid');
                if($openID){
                    //给用户发送发货信息（微信）
                    $template = array('touser' => $openID,
                        'template_id' => "6XzrU2rCZ3fSb1ffbtWuHFnL9EvKy8isk3KNm0_DhgE",
                        'url' => WEIXIN_URL."/Order/waitSend.html",
                        'topcolor' => "#7b68ee",
                        'data' => array('first' => array('value' => urlencode("您好,您购买的商品已经为您发货："),
                                'color' => "#000000",
                            ),
                            'delivername' => array('value' => $express_id,
                                'color' => "#000000",
                            ),
                            'ordername' => array('value' => $shipping_code,
                                'color' => "#000000",
                            ),
                            'remark' =>array('value'=>urlencode("\\n商品名称：".$goods_title."\\n如有疑问请拨打客服电话：4000371775！或者直接加客服微信号：dtgou1"),
                                'color'=>"#000000",
                            ),
                        )
                    );
                    $result = urldecode(json_encode($template));
                    $kefu = new \Libs\WeiXin\CustomService();
                    $kefu->send_template_message($result);
                }
            }
            
            
            $html = "修改订单[".$order_id."]状态为".$a.",快递公司：".$express_id.",快递单号【".$shipping_code."】";
            $logobj->write(array("管理员:".session('manager_auth.username'),"订单状态",$html));
            $this->success('发货成功!');

        }else{

            $id = I('order_id');
            $map['order_id']=$id;
            $order = D('Order')->relation('OrderCommon')->where($map)->find();//订单信息
            $reciver_info = unserialize($order['OrderCommon']['reciver_info']);
            $orderGoods = M('orderGoods')->where($map)->select();//订单商品信息
            $express = M('express')->select();//物流公司信息
            $this->assign('express',$express);
            $this->assign('reciver_info',$reciver_info);
            $this->assign('orderGoods',$orderGoods);
            $this->assign('order',$order);
            $this->assign('action', 'order');
            $this->display();
        }
    }
    
    
    public function getGoods() {
        $map['order_id'] = I('order_id');
        $re = M('orderGoods')->where($map)->select();
        $str = "";
        foreach ($re as $key => $value) {
            $str .= "<tr>";
            $str .= "<td><a href=".HOME_URL."/Goods/".$value['goods_id']." target=\"_blank\"><img style=\"width: 80px;display: block;\" src=\"{$value['goods_image']}\"/></a></td>";
            $str .= "<td>".$value['goods_title']."</td>";
            $str .= "<td>".$value['goods_price']."</td>";
            $str .= "<td>".$value['goods_num']."</td>";
            $str .= "<td>".$value['goods_attri_info']."</td>";
            $str .= "</tr>";
        }
        $arr['str'] = $str;
        return $this->ajaxReturn($arr);
    }

    //订单查询
    public function orderInquiry(){
        if(IS_POST){
            $p = I('post.');

//            $mOrder = D('Order');
//            //$p['order_sn'] ? $where['tdd_order.order_sn'] = $p['order_sn'] : false; //订单号
//            $p['buyer_name'] ? $where['reciver_name'] = $p['buyer_name'] : false; //收货人
//
//            $mOrder->condition($where);
//            $re = $mOrder->relation('OrderCommon')->where($where)->select();
//            p($mOrder->getLastSql());
//            exit;

            $p['order_sn'] ? $where['tdd_order.order_sn'] = $p['order_sn'] : false; //订单号
            $p['pay_sn'] ? $where['tdd_order.pay_sn'] = $p['pay_sn'] : false; //支付单号
            $p['store_name'] ? $where['tdd_order.store_name'] = $p['store_name'] : false; //卖家店铺
            $p['buyer_email'] ? $where['tdd_order.buyer_email'] = $p['buyer_email'] : false; //电子邮箱
            $p['shipping_code'] ? $where['tdd_order.shipping_code'] = $p['shipping_code'] : false; //物流单号
            $p['payment_code'] ? $where['tdd_order.payment_code'] = $p['payment_code'] : false; //付款方式
            $p['order_state'] ? $where['tdd_order.order_state'] = $p['order_state'] : false; //订单状态
            if($p['query_start_time'] && $p['query_end_time']){
                $where['tdd_order.add_time'] = array(array('EGT',$p['query_start_time']),array('ELT',$p['query_end_time']));//两个时间同时存在
            }else{
                $p['query_start_time'] ? $where['tdd_order.add_time'] = array('EGT',$p['query_start_time']) : false; //只有开始时间
                $p['query_end_time'] ? $where['tdd_order.add_time'] = array('ELT',$p['query_end_time']) : false; //只有结束时间
            }

            $p['buyer_name'] ? $where['tdd_order_common.reciver_name'] = $p['buyer_name'] : false; //收货人
            $p['user_provinceid'] ? $where['tdd_order_common.reciver_province_id'] = $p['user_provinceid'] : false; //省
            $p['user_cityid'] ? $where['tdd_order_common.reciver_reciver_city_id'] = $p['user_cityid'] : false; //市
            $p['user_areaid'] ? $where['tdd_order_common.reciver_areaid_id'] = $p['user_areaid'] : false; //县（区）

            $p['phone'] ? $where['tdd_order_common.reciver_info'] = array('like','%'.$p['phone'].'%') : false; //手机号

            $Order = M("order");
            $count = $Order->join('LEFT JOIN tdd_order_common ON tdd_order.order_id = tdd_order_common.order_id')->where($where)->count();
            $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)

            $show = $Page->show(); // 分页显示输出
            $arr = $Order->join('LEFT JOIN tdd_order_common ON tdd_order.order_id = tdd_order_common.order_id')->where($where)->order('tdd_order.order_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
            
            $this->assign('pages',$show);
            $this->assign('arr',$arr);
            p($Order->getLastSql());
            p($where);
            p($arr);die;
            $this->display('index');die;
        }

        $this->display();
    }
    
    //退款管理
    public function refund(){
        $order_sn = I('order_sn');
        $buyer_name = I('buyer_name');
        $payment_code = I('payment_code');
        $query_start_time = strtotime(I('query_start_time'));
        $query_end_time = strtotime(I('query_end_time'));
        if(!empty($query_end_time)){
            $query_end_time = time();
        }
        
        if(!empty($order_sn)){
            $where['order_sn'] = $order_sn;
        }
        
        if(!empty($buyer_name)){
            $where['user_name'] = $buyer_name;
        }
        
        if(!empty($payment_code)){
            $where['payment_code'] = $payment_code;
        }
        
        if(!empty($query_end_time) && !empty($query_end_time)){
            $where['add_time'] = array('between',array($query_start_time,$query_end_time));
        }
        $where['refund_state'] = 1;
        $where['order_state'] = 20;
        $Order = M("order");
        $count = $Order->where($where)->count();
        $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        
        $show = $Page->show(); // 分页显示输出
        $arr = $Order->where($where)->order('order_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('pages',$show);
        $this->assign('arr',$arr);
        $this->assign('action', 'refund');
        $this->display();
    }

    //取消订单
    public function cancel(){
        $data['order_id'] = I('data');
        if(M('order')->where($data)->save(array('order_state'=>0))){
            //取消订单的同时将用户使用的优惠券返还给用户
            $pay_sn = M('order')->where(array('order_id'=>I('data')))->getField('pay_sn');
            if($pay_sn){
                $map['pay_sn'] = $pay_sn;
                $list = M('orderVoucher')->where($map)->find();
                if($list){
                    M('pVoucher')->where(array('voucher_id'=>$list['voucher_code']))->save(array('voucher_state'=>1));
                }
            }
            $this->success('订单已取消！');
        }else{
            $this->error('订单取消失败！');
        }
    }
    
}
